<?php

namespace App\Http\Handler;

use App\Exceptions\FrameException;
use App\Exceptions\IllegalRequestException;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;
use Framework\Foundation\Response\ResponseGen;
use App\Constants\Common\HttpStatusCode;

class RestMainHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        try {
            $restDispatchInfo = $request->getAttribute('restDispatchInfo');

            list($controller, $targetMethod) = explode('@', $restDispatchInfo[1]['action']);


            if ('\\' !== substr($controller, 0, 1)) {
                $controllerClass = '\App\Http\Rest\\' . str_replace('/', '\\', ucwords($controller, '/'));
            } else {
                $controllerClass = $controller;
            }

            if (!class_exists($controllerClass)) {
                throw new IllegalRequestException("restFul控制器不存在", HttpStatusCode::GONE);
            }

//          return (new $controllerClass)->{$method}($request);
            $response = call_user_func([new $controllerClass, $targetMethod], $request);
            if ($response instanceof ResponseInterface) {
                return $response;
            }

            return ResponseGen::success($response, "操作成功");
        } catch (FrameException $e) {
            return ResponseGen::error($e->getCode(), $e->getMessage(), $e->getErrData());
        } catch (\Throwable $throwable) {
            return ResponseGen::error($throwable->getCode(), $throwable->getMessage());
        }
    }
}
